#!/bin/python

import socket
import sys
import os
import time
from tester import *
from compiler import *
import threading
class ctservice:
    def __init__(self,host="localhost",port=1234,debug=False,cached=True):
        self.host = host
        self.port = port
        self.ssocket=socket.socket()
        self.ssocket.bind((self.host,self.port))
        self.ssocket.listen(5)
        self.requestlist=[]
        self.debug = debug
    def serve(self):
        print 'C&T Service is running at ', self.host, ' on port ', self.port
        while True:
            client,addr = self.ssocket.accept()
            h = ctservice.handleconn(client,self.debug)
            self.requestlist.append(h)
            h.start()
            
            
    class handleconn(threading.Thread):
        tid=0
        def __init__(self,socket,debug):
            self.conn = socket
            self.debug = debug
            threading.Thread.__init__(self)
            self.myid = ctservice.handleconn.tid
            ctservice.handleconn.tid+=1
        def run(self):
            header = self.conn.recv(1024)  # header format: user@proid@file-length, file length used to control the loop of recvieving data.
            args = header.split('@')
            filename = args[0]+args[1]+".c"
            print repr(header)
            self.conn.send('1')  #send 1 to client, confirm that has recvieve the headers.
            if self.debug:
                print time.ctime()," Thread-",self.myid," : Recvieve source of problem ", args[1]," commited by ",args[0]
            source=""
            while len(source)<int(args[2]):
                source+= self.conn.recv(1024)
            fout = open(filename,'w')
            fout.write(source)
            fout.flush()
            os.fsync(fout)
            fout.close()
            cp = Compiler()
            r = cp.compile_source(filename)
            if r[0]==0:
                te = Tester()
                r.append(te.test_(filename[:-2]+".out",args[1]))
                
            if self.debug:
                if r[0]==-1:
                    print time.ctime()," Thread-", self.myid," : Compiled failed. "
                    print "Caused by: ", r[1]
                if r[0]==0:
                    if r[2]==0:
                        print time.ctime()," Thread-", self.myid," : Test pass."
                    if r[2]==-1:
                        print time.ctime()," Thread-", self.myid," : Do not match answer."
                    if r[2]==-2:
                        print time.ctime()," Thread-", self.myid," : Runtime error."
                    if r[2]==-3:
                        print time.ctime()," Thread-", self.myid," : Take too long time to run the code."
            self.conn.send(str(r))
            self.conn.close()
            
def help():
    print """USAGE:
    [-h hostname or ip address, default="localhost"]
    [-p port to linsten, default=1234]
    [-debug, print debug infomation ,default=False]"""           
            
def test():
        ct = None
        port=1234
        host='localhost'
        debug=False
        args={'-h':'localhost','-p':1234,'-debug':True}
        for i in range(1,len(sys.argv)-1):
            if sys.argv[i] in args:
                if sys.argv[i] == '-debug':
                    args['-debug'] = True
                else:
                    args[sys.argv[i]] = sys.argv[i+1]
        if len(sys.argv)==2 and sys.argv[1]=='--help':
            help()
            sys.exit()
        ct = ctservice(args['-h'],args['-p'],args['-debug'])
        ct.serve()
if __name__ == "__main__":
    test()
       
            
